<script setup>
import { ref } from 'vue'
import { fetchIndices3dData } from '../api/weatherAPI'
import { watch } from 'vue'
import { useCityStore } from '../stores/cityStore'
import { useRoute } from 'vue-router'

const cityStore = useCityStore()
const route = useRoute()
const id = ref('')
id.value = route.params.id

import dayjs from 'dayjs'
import weekday from 'dayjs/plugin/weekday'
dayjs.extend(weekday)

watch(
  //第一个参数（必选）：监听的数据源
  () => cityStore.location,
  //第二个参数（必选）：回调函数，当数据源有变化时需要做的事情
  () => {
    getData(cityStore.location.id)
    // city = ref()
  },
  //第三个函数（可选）：即使回调，初始状态执行一次回调函数
  { immediate: true }
)

//三天生活指数
const Indices3dDaily = ref([])
//生活指数详情
const Indices3d = ref([])
//网络请求，获取后台数据
async function getData(locationID) {
  const res = await fetchIndices3dData(locationID, id.value)
  console.log(res)
  Indices3dDaily.value = res.daily
  Indices3d.value = res.daily[0]
}

// 获取当前日期的零点，将时间设为当天的0点
const today = dayjs().startOf('day')

// 日期格式化和判断函数
function formatDateAndLabel(dateStr) {
  // 将传入的日期转换为当天的零点
  const date = dayjs(dateStr).startOf('day')
  // 计算与当前日期的天数差
  const diffDays = date.diff(today, 'day')
  const weekDays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
  let label = ''
  if (diffDays === 0) {
    label = '今天'
  } else if (diffDays === 1 || diffDays === 2) {
    // 显示周几
    label = weekDays[date.day()]
  } else {
    // 处理其他日期，显示原始日期
    label = date.format('MM月DD日')
  }
  return {
    label,
    // 格式化日期
    formattedDate: date.format('MM月DD日'),
  }
}
</script>

<template>
  <div class="living-index-detail">
    <!-- <h1>生活指数详情页面{{ id }}</h1> -->
    <div class="name">{{ Indices3d.name }}</div>
    <div>
      <li v-for="(item, i) in Indices3dDaily" :key="i">
        <div class="date">
          <div>{{ formatDateAndLabel(item.date).label }}</div>
          <div>{{ formatDateAndLabel(item.date).formattedDate }}</div>
        </div>
        <!-- <img :src="getIconPath(item.name)" alt="icon" class="index-icon" /> -->

        <div class="two">
          <p>{{ item.category }}</p>
          <p>{{ item.text }}</p>
        </div>
      </li>
    </div>
  </div>
</template>

<style scoped>
.living-index-detail {
  width: 100%;
  margin: 1rem 0rem;
  padding: 2rem;
  background: rgba(226, 226, 227, 0.756);
  border-radius: 1rem;
  overflow: hidden;
}

.living-index-detail > div:nth-of-type(2) > li {
  list-style: none;
  border-radius: 0.5rem;
  padding: 1rem;
  margin: 1rem 0;
  font-size: 1.2rem;
  display: flex;
}
.date {
  flex: 1;
  display: flex;
  align-items: center;
  flex-direction: column;
  justify-content: center;

  font-weight: bold;
}
.two {
  flex: 7;
  padding: 10px 20px;
  background: white;
  border-radius: 0.5rem;
}
.two > p:nth-of-type(1) {
  padding: 0.5rem 0.5rem;
  border-radius: 0.5rem;
  margin: 0.5rem 0;
  background: #c0be49;
  color: white;
}
.two > p:nth-of-type(2) {
  padding: 0.5rem 0.5rem;
  margin: 0.5rem 0;
  color: #606060;
}
.name {
  font-size: 1.5rem;
}
</style>